<template>
<!-- 组件封装 关注按钮 -->
<!-- 模板只能有一个根节点。这里是if else 所以是没问题的 -->
  <van-button
    v-if="isFollowed"
    class="follow-btn"
    round
    size="small"
    @click="onFollow"
    :loading="loading"
  >
    已关注
  </van-button>
  <van-button
    v-else
    @click="onFollow"
    :loading="loading"
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
  >
    关注
  </van-button>
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'
export default {
  name: 'followUser',
  // 自定义 v-model 接收的参数名称
  model: {
    prop: 'isFollowed', // 默认value
    event: 'update-is_followed' // 默认input
  },
  props: {
    isFollowed: {
      type: Boolean,
      require: true
    },
    userId: {
      type: [Number, String, Object],
      require: true
    }
  },
  data () {
    return {
      loading: false
    }
  },
  methods: {
    // 关注和取消关注用户
    async onFollow () {
      this.loading = true // 展示关注按钮的 loading 状态
      try {
        if (this.isFollowed) {
          await deleteFollow(this.userId)
        } else {
          await addFollow(this.userId)
        }
        this.$emit('update-is_followed', !this.isFollowed)
      } catch (err) {
        let message = '关注操作失败'
        if (err.response && err.response.status === 410) {
          message = '不能关注自己'
        }
        this.$toast(message)
      }
      // 关闭按钮的loading
      this.loading = false
    }
  }
}
</script>

<style>

</style>
